package com.heima.common.exception;

import com.heima.common.dtos.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice //声名当前类为统一异常处理类
public class BaseExceptionCatch {

    /**
     * 处理 运行时异常
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseResult runTimeExceptionHandler(RuntimeException e){
        return ResponseResult.error(1,e.getMessage());
    }

    @ExceptionHandler(LeadException.class)
    public ResponseResult leadExceptionHandler(LeadException e){
        return ResponseResult.error(e.getStatus(),e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult methodArgumentNotValidException(MethodArgumentNotValidException e){

//        获取返回的错误集合
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
//        String errorMsg = "";
//        for (ObjectError objError : allErrors) {
//            String msg = objError.getDefaultMessage();
//            if(errorMsg.length()>0){
//                errorMsg +=",";
//            }
//            errorMsg += msg;
//        }
        String errorMsg = allErrors.
                stream().
                map(ObjectError::getDefaultMessage).
                collect(Collectors.joining(","));

        return ResponseResult.error(1020,errorMsg);
    }
}
